import { sendMessage, chunkArray } from "../utils";
import type { FormatSaveParamsFn, GetProductBySkuMapFn } from "../type";
import { ACTION_TYPE } from "@/constants/actionType";

let tempAntiContent: any = "";
let unToConfirmPriceReviewOrderCount = 0;
let temuDisplayPriceMultiplier = 1;

// 列表名接口
function getPageDataUrl() {
  return `${location.origin}/api/kiana/magnus/mms/price-adjust/page-query`;
}
// 议价接口
function getDoAgreeToNegotiateUrl() {
  return `${location.origin}/api/kiana/magnus/mms/price-adjust/batch-review`;
}

// 获取当前页数
function getCurrentPage() {
  return Number(
    document.querySelector('[class*="pagerItemActive"]')?.textContent || 1
  );
}
function getErpSkuMathField() {
  return "skuNoGenerate";
}

// 从ERP获取sku的采购价的时候需要乘上赔率
function formatSourcePrice(price: any) {
  return price * temuDisplayPriceMultiplier;
}

// 获取PageSize
function getPageSize() {
  const pageSizeText =
    document.querySelector(
      '[data-testid="beast-core-pagination"] [class*="mirror"]'
    )?.textContent || "";
  return Number(pageSizeText.match(/^\d+/)?.[0] || 10);
}

function getAntiContent() {
  if (tempAntiContent) {
    return Promise.resolve(tempAntiContent);
  }
  return sendMessage({
    type: "getAntiContent",
  }).then((data) => {
    tempAntiContent = data || "";
  });
}

function getRequestHeaders() {
  const mallId = localStorage.getItem("agentseller-mall-info-id") || "";
  return {
    "Content-Type": "application/json",
    "Anti-Content": tempAntiContent,
    Mallid: mallId,
  };
}

// 获取总页数
function getTotalPageSize() {
  const endPageElement = document
    .querySelector('[data-testid="beast-core-pagination"]')
    ?.querySelector('[class*="pagerItem"]:nth-last-child(2)');

  return Number(endPageElement?.textContent || 1);
}
// 格式化列表数据
function formatListDataToMap({
  data,
  skuCodeList,
  productBySkuAndCostPriceMap,
  productBySkuCurrencyMap,
}: {
  data: any[];
  skuCodeList: any[];
  productBySkuAndCostPriceMap: any;
  productBySkuCurrencyMap: any;
}) {
  return data.reduce((obj, dataItem: any) => {
    const { id, skuInfoItemList, newSupplyPrice } = dataItem;
    if (id && skuInfoItemList && skuInfoItemList.length) {
      obj[id] = {
        skuPriceMap: {},
        skuNoGenerateInfoList: [],
      };
      skuInfoItemList.forEach((skuItem: any) => {
        const { spec, skuExtCode, priceBeforeExchange, priceCurrency } =
          skuItem;
        const key = skuExtCode || spec;
        obj[id].skuPriceMap[key] = newSupplyPrice;
        if (skuExtCode) {
          obj[id].skuNoGenerateInfoList.push({
            skuNoGenerate: skuExtCode,
            verifiedPrice: newSupplyPrice / temuDisplayPriceMultiplier,
            verifiedCurrencyType: priceCurrency,
          });
        }
        skuCodeList.push(key);
        productBySkuAndCostPriceMap[key] = priceBeforeExchange;
        productBySkuCurrencyMap[key] = priceCurrency;
      });
    }

    return obj;
  }, {});
}

function findTrByText(text: string) {
  // 获取 container 下的 root 元素下的 table
  const table = document.querySelector("#container #root table");

  if (!table) {
    console.error("未找到指定的表格");
    return null;
  }

  // 获取表格中所有的 tr 元素
  const trs = table.querySelectorAll("tr");
  const trArray = Array.from(trs);
  // 遍历每个 tr
  for (const tr of trArray) {
    // 获取当前 tr 中第四个 td（索引为 3，因为从 0 开始计数）
    const td = tr.querySelector("td:nth-child(4)");

    if (!td) continue;

    // 获取 td 中的 p 元素
    const p = td.querySelector("p");

    if (p && p.textContent && p.textContent.trim() === text.trim()) {
      // 找到匹配的 tr，返回它
      return tr;
    }
  }

  // 如果没有找到匹配的 tr，返回 null
  return null;
}

function getEighthTdNumber(tr: any) {
  // 获取所有td元素
  const tds = tr?.querySelectorAll("td");

  // 检查是否有第八个td（索引从0开始，所以是7）
  if (tds.length > 7) {
    const eighthTd = tds[7];
    const content = eighthTd.textContent || eighthTd.innerText;

    // 提取数字（包括整数、小数、负数）
    const numberMatch = content.match(/-?\d+(\.\d+)?/);

    if (numberMatch) {
      return parseFloat(numberMatch[0]);
    }
  }

  // 如果没有第八个td或没有找到数字，返回null
  return null;
}

const handleGetDisplayNewSupplyPrice = (skuCode: string) => {
  const currentSkuCodeTr = findTrByText(skuCode);
  const tdNumber = getEighthTdNumber(currentSkuCodeTr);
  return tdNumber;
};

const getDataIndexPriceMultiplier = (data: any, index: any) => {
  let priceMultiplier = 0;
  const spec = data[index]?.skuInfoItemList?.[0]?.spec;
  const newSupplyPrice = data[index]?.newSupplyPrice;
  const displayNewSupplyPriceNumber = handleGetDisplayNewSupplyPrice(spec);

  if (newSupplyPrice && displayNewSupplyPriceNumber) {
    // 提取匹配到的数字并转换为数值类型
    priceMultiplier = newSupplyPrice / displayNewSupplyPriceNumber;
  }
  return Math.round(priceMultiplier);
};

// 获取商品列表中的信息
const getProductBySkuMap: GetProductBySkuMapFn = async ({
  pageNum = 1,
  pageSize = 10,
  skuCodeList = [],
  productBySkuAndCostPriceMap = {},
  productBySkuCurrencyMap = {},
}) => {
  const pageDataUrl = getPageDataUrl();
  await getAntiContent();
  const headers = getRequestHeaders();
  const skcResponse = await fetch(pageDataUrl, {
    method: "POST",
    headers,
    body: JSON.stringify({
      pageInfo: {
        pageNo: pageNum,
        pageSize,
      },
      saleForbidOrder: false,
      status: 1,
      trafficLowExpose: false,
    }),
  }).then((res) => res.json());
  const skcData = skcResponse?.result?.list || [];
  const length = skcData.length;
  if (skcData.length) {
    temuDisplayPriceMultiplier = 0;
    const firstIndexMultiplier = getDataIndexPriceMultiplier(
      skcData,
      length - 1
    );
    if (firstIndexMultiplier) {
      if (skcData.length > 1) {
        const secondIndexMultiplier = getDataIndexPriceMultiplier(
          skcData,
          length - 2
        );
        if (firstIndexMultiplier === secondIndexMultiplier) {
          temuDisplayPriceMultiplier = firstIndexMultiplier;
        } else {
          const errorMessage = `价格比例不一致,请刷新页面并在调价页面选择"待卖家确认"tab`;
          alert(errorMessage);
          throw new Error(errorMessage);
        }
      } else {
        temuDisplayPriceMultiplier = firstIndexMultiplier;
      }
    }
  }
  if (!temuDisplayPriceMultiplier) {
    const errorMessage = `获取不到价格比例,请刷新页面并在调价页面选择"待卖家确认"tab`;
    alert(errorMessage);
    throw new Error(errorMessage);
  }

  return formatListDataToMap({
    data: skcData,
    skuCodeList,
    productBySkuAndCostPriceMap,
    productBySkuCurrencyMap,
  });
};

// 操作时格式化数据
const formatSaveParams: FormatSaveParamsFn = ({
  productBySkuMap,
  skuPurchasePriceMap,
  multiplier,
  actionType,
}) => {
  const submitOrders: any[] = [];
  let successTotal = unToConfirmPriceReviewOrderCount;
  let skipCount = 0;
  unToConfirmPriceReviewOrderCount = 0;
  const updateBatchBysSkuNoGenerateParams: any[] = [];
  for (const adjustId of Object.keys(productBySkuMap)) {
    const { skuPriceMap, skuNoGenerateInfoList } = productBySkuMap[adjustId];
    let isSkip = false;
    for (const skuCode of Object.keys(skuPriceMap)) {
      const hasErpData = skuCode in skuPurchasePriceMap;
      if (!hasErpData) {
        isSkip = true;
        break;
      }
      const skuPriceNumber = Number(skuPriceMap[skuCode]);
      const contrastNumber =
        Number(skuPurchasePriceMap[skuCode]) * Number(multiplier);
      if (actionType === ACTION_TYPE.AGREE) {
        // 同意建议价, 如果"核算源价" x "倍率"比"平台建议价"小则符合同意条件
        if (contrastNumber < skuPriceNumber) {
          // 执行
        } else {
          // 否则跳过
          isSkip = true;
        }
      } else if (actionType === ACTION_TYPE.REFUSE) {
        // 拒绝建议价, 如果"核算源价" x "倍率"比"平台建议价"大则符合拒绝条件
        if (contrastNumber > skuPriceNumber) {
          // 执行
        } else {
          isSkip = true;
          // 否则跳过
        }
      }
    }
    if (isSkip) {
      skipCount++;
    } else if (actionType === ACTION_TYPE.AGREE) {
      updateBatchBysSkuNoGenerateParams.push(...(skuNoGenerateInfoList || []));
      successTotal++;
      submitOrders.push(adjustId);
    } else if (actionType === ACTION_TYPE.REFUSE) {
      submitOrders.push(adjustId);
      successTotal++;
    }
  }
  temuDisplayPriceMultiplier = 0;
  if (!submitOrders.length) {
    return { paramsList: [], successTotal, skipCount };
  }
  const paramsList = chunkArray(submitOrders, 500)
    .map((item) => {
      return item;
    })
    .map((item) => {
      const params: any = {
        submitOrders: item,
      };
      if (actionType === ACTION_TYPE.AGREE) {
        params.batchResult = 1;
      } else if (actionType === ACTION_TYPE.REFUSE) {
        params.batchResult = 2;
        params.rejectReasons = item.reduce((obj: any, id: any) => {
          obj[id] = "建议价格过低";
          return obj;
        }, {});
      }
      return params;
    });
  return {
    paramsList,
    successTotal,
    skipCount,
    updateBatchBysSkuNoGenerateParams,
  };
};

export default {
  getCurrentPage,
  getPageSize,
  getTotalPageSize,
  getProductBySkuMap,
  formatSaveParams,
  getDoAgreeToNegotiateUrl,
  getRequestHeaders,
  getErpSkuMathField,
  formatSourcePrice,
};
